package com.manage;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.manage.base.BaseActivity;
import com.manage.db.MenuTypeDBAdapter;
import com.manage.http.AsyncHttpGet;
import com.manage.http.DefaultThreadPool;
import com.manage.http.RequestException;
import com.manage.http.RequestParameter;
import com.manage.http.RequestResultCallback;
import com.manage.model.Shop;
import com.manage.service.AppService;
import com.manage.service.ICallback;
import com.manage.service.IService;
import com.manage.sharedpreferences.SPConfig;
import com.manage.util.RequestUtils;
import com.manage.util.ToastUtils;
import com.manage.widgets.CustomDialog;
import com.manage.widgets.CustomProgressDialog;
import com.manage.widgets.DialogActionListener;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 商家管理首页
 * @author liyoro
 *
 */
public class ManageActivity extends BaseActivity implements OnClickListener {
	
	private static String TAG = "ManageActivity";
	
	private TextView tvShopName = null; // 商户名
	private TextView tvLastLoginTime = null; // 最后登录时间
	private TextView tvSuccessfulOrders = null; // 成功订单数
	private TextView tvTotalEvaluation = null; // 总评价数
	private TextView tvTaste = null; // 口味
	private TextView tvSpeed = null; // 速度
	private TextView tvService = null; // 服务
	private TextView tvTurnover = null; // 营业额
	
	private TextView tvAcceptOrderContent = null; // 待受理订单
	private TextView tvPendingDeliveryOrders = null;  // 待配送订单
	private TextView tvPendingAccountedOrders = null;  // 待入帐订单
	
	private TextView tvSuspendBusiness = null; // 暂停营业
	
	private RelativeLayout layoutAcceptOrder = null;
	private RelativeLayout layoutPendingDeliveryOrders = null;
	private RelativeLayout layoutPendingAccountedOrdersr = null;
	private RelativeLayout layoutAccountsStatistics = null;
	private RelativeLayout layoutCheckOrderEvaluation = null;
	private RelativeLayout layoutSuspendBusiness = null;
	private RelativeLayout layoutQuit = null;
	
	private CustomDialog quitDialog = null;  
	
	/**
	 * 取LoginActivity中从服务器返回的数据
	 */
	private Shop mShop = null;
	
	CustomProgressDialog loginOutDialog = null; //退出账号时的dialog
	
	private MenuTypeDBAdapter mDBAdapter;
	
//==============================================================================================
	/**
	 * 注册connection
	 */
	private ServiceConnection mConnection = new ServiceConnection() {

		@Override
	    public void onServiceDisconnected(ComponentName name) {
			Log.d(TAG, "onServiceDisconnected");
	       	mService = null;
	  	}

	  	@Override
	   	public void onServiceConnected(ComponentName name, IBinder service) {
	  		Log.d(TAG, "onServiceConnected");
	      	mService = IService.Stub.asInterface(service);
	     	try {
	        	mService.registerCallback(mCallback);
	       	} catch (RemoteException e) {
	           	Log.e(TAG, "", e);
	     	}
	  	}
	};
	    
	/**
	 * service的回调方法
	 */
	private ICallback.Stub mCallback = new ICallback.Stub() {
	    	
		@Override
		public void refresh() {
			sendRefreshCommand();
		}
	};
	    
	private boolean flag = true;
	    
	// 发送刷新消息
	public void sendRefreshCommand() {
		new Thread() {
			public void run() {
				while (flag) {
	 				try {
	 					System.out.println("sleep");
	 					Thread.currentThread().sleep(60*1000);
	 				} catch (Exception e) {
	 					System.out.println("error");
	 				}

	 				refreshDatas();
				}
			}
		}.start();
	}
	 	
	//刷新数据的服务
	private IService mService;

//==============================================================================================
	 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		//友盟app更新
		UmengUpdateAgent.setUpdateOnlyWifi(false);
		
		UmengUpdateAgent.setUpdateAutoPopup(false);
		UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() {
		        @Override
		        public void onUpdateReturned(int updateStatus, UpdateResponse updateInfo) {
		            switch (updateStatus) {
		            case 0: // has update
		                UmengUpdateAgent.showUpdateDialog(mContext, updateInfo);
		                break;
		            case 1: // has no update
		                Toast.makeText(mContext, "没有更新", Toast.LENGTH_SHORT)
		                        .show();
		                break;
		            case 2: // none wifi
		                Toast.makeText(mContext, "没有wifi连接， 只在wifi下更新", Toast.LENGTH_SHORT)
		                        .show();
		                break;
		            case 3: // time out
		                Toast.makeText(mContext, "超时", Toast.LENGTH_SHORT)
		                        .show();
		                break;
		            }
		        }
		});

		UmengUpdateAgent.update(this);
		
		this.setContentView(R.layout.activity_manage);
		
		initDatas();

		Intent i = new Intent(this, AppService.class);
        bindService(i, mConnection, Context.BIND_AUTO_CREATE);
	}

	@Override
	protected void onStart() {
		
		super.onStart();
	}

	@Override
	protected void onResume() {
		Log.i(TAG, "onResume");
		sp.setBoolean(SPConfig.NOTIFY, false);
		super.onResume();
		refreshDatas();
	}
	
	@Override
	protected void onRestart() {
		Log.i(TAG, "onRestart");
		super.onRestart();
		refreshDatas();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(mService!=null){
            try {
                mService.unregisterCallback(mCallback);
            } catch (RemoteException e) {
                Log.e(TAG, "", e);
            }
        }
        //destroy的时候不要忘记unbindService
        unbindService(mConnection);
	}

	@Override
	public String getLeftBtnName() {
		return null;
	}

	@Override
	public String getTitleName() {
		return this.getString(R.string.manage_home);
	}

	@Override
	public boolean showButton() {
		return false;
	}

	@Override
	public void initView() {
        tvShopName = (TextView)findViewById(R.id.tv_shop_name);
        tvLastLoginTime = (TextView)findViewById(R.id.tv_last_login_time);
        tvSuccessfulOrders = (TextView)findViewById(R.id.tv_successful_orders);
        tvTotalEvaluation = (TextView)findViewById(R.id.tv_total_evaluation);
        tvTaste = (TextView)findViewById(R.id.tv_taste);
        tvSpeed = (TextView)findViewById(R.id.tv_speed);
        tvService = (TextView)findViewById(R.id.tv_service);
        tvTurnover = (TextView)findViewById(R.id.tv_turnover);
        
        tvSuspendBusiness  = (TextView)findViewById(R.id.tv_suspend_business);
        
        tvAcceptOrderContent = (TextView)findViewById(R.id.tv_accept_order_content);
        tvPendingDeliveryOrders = (TextView)findViewById(R.id.tv_pending_delivery_orders);
        tvPendingAccountedOrders = (TextView)findViewById(R.id.tv_pending_accounted_orders);
        
        // 管理选项
        layoutAcceptOrder = (RelativeLayout)findViewById(R.id.layout_accept_order);
    	layoutPendingDeliveryOrders = (RelativeLayout)findViewById(R.id.layout_pending_delivery_orders);
    	layoutPendingAccountedOrdersr = (RelativeLayout)findViewById(R.id.layout_pending_accounted_orders);
    	layoutAccountsStatistics = (RelativeLayout)findViewById(R.id.layout_accounts_statistics);
    	layoutCheckOrderEvaluation = (RelativeLayout)findViewById(R.id.layout_check_order_evaluation);
    	layoutSuspendBusiness = (RelativeLayout)findViewById(R.id.layout_suspend_business);
    	layoutQuit = (RelativeLayout)findViewById(R.id.layout_quit);
    	
    	layoutAcceptOrder.setOnClickListener(this);
    	layoutPendingDeliveryOrders.setOnClickListener(this);
    	layoutPendingAccountedOrdersr.setOnClickListener(this);
    	layoutAccountsStatistics.setOnClickListener(this);
    	layoutCheckOrderEvaluation.setOnClickListener(this);
    	layoutSuspendBusiness.setOnClickListener(this);
    	layoutQuit.setOnClickListener(this);
    	
    	mDBAdapter = new MenuTypeDBAdapter(this);
	}

	@Override
	public void initDatas() {
		sp.setBoolean(SPConfig.NOTIFY, false);
		
		/**
		 * 取LoginActivity中从服务器返回的数据
		 */
		mShop = (Shop)getIntent().getSerializableExtra(SER_KEY);     
		
		if(mShop != null) {
			tvShopName.setText(mShop.getShopName());
	        tvLastLoginTime.setText(mShop.getLastLoginTime());
	        tvSuccessfulOrders.setText(mShop.getSuccessfulOrders());
	        tvTotalEvaluation.setText(mShop.getTotalEvaluation());
	        
	        if(mShop.getTaste().length() > 2) {
	        	tvTaste.setText(mShop.getTaste().substring(0, 3));
	        } else {
	        	tvTaste.setText(mShop.getTaste());
	        }
	        
	        if(mShop.getSpeed().length() > 2) {
	        	tvSpeed.setText(mShop.getSpeed().substring(0, 3));
	        } else {
	        	tvSpeed.setText(mShop.getSpeed());
	        }
	        
	        if(mShop.getService().length() > 2) {
	        	tvService.setText(mShop.getService().substring(0, 3));
	        } else {
	        	tvService.setText(mShop.getService());
	        }
	        
	        tvTurnover.setText(mShop.getTurnover());
			
	        tvAcceptOrderContent.setText(mShop.getAcceptOrder());
	        tvPendingDeliveryOrders.setText(mShop.getDeliverOrder());
	        tvPendingAccountedOrders.setText(mShop.getIncomeOrder());
	        
	        /**
	         * 程序的默认设置，“暂停/恢复营业”
	         */
	        initSuspendBusiness();
		}
	}
	
	/**
	 * 刷新数据
	 */
	private void refreshDatas() {
		sp.setBoolean(SPConfig.NOTIFY, true);
		String name = sp.getString(SPConfig.USERNAME, "");
		String pass = sp.getString(SPConfig.PASSWORD, "");
		
		RequestUtils.getShopInfo(name, pass, handler, this.requestList, ManageActivity.this);
	}

	@Override
	public void onClick(View v) {
		int viewID = v.getId();
		switch(viewID) {
		case R.id.layout_accept_order:
			if(layoutAcceptOrder.isClickable()) {
				if(tvAcceptOrderContent.getText().equals("0")) {
					Toast.makeText(this, "暂无待受理订单！", Toast.LENGTH_SHORT).show();
				} else {
					manageAccepted();
				}
			}
			break;
		case R.id.layout_pending_delivery_orders:
			if(layoutPendingDeliveryOrders.isClickable()) {
				if(tvPendingDeliveryOrders.getText().equals("0")) {
					Toast.makeText(this, "暂无待配送订单！", Toast.LENGTH_SHORT).show();
				} else {
					manageDelivery();
				}
			}
			break;
		case R.id.layout_pending_accounted_orders:
			if(layoutPendingAccountedOrdersr.isClickable()) {
				if(tvPendingAccountedOrders.getText().equals("0")) {
					Toast.makeText(this, "暂无待入帐订单！", Toast.LENGTH_SHORT).show();
				} else {
					manageAccounted();
				}
			}
			break;
		case R.id.layout_accounts_statistics:  //查看统计
			manageStatistics();
			break;
		case R.id.layout_check_order_evaluation:  //查看评价
			manageEvaluation();
			break;
		case R.id.layout_suspend_business: //暂停营业
			manageSuspendBusiness();
			break;
		case R.id.layout_quit:  //退出帐号
			quit();
			break;
		}
	}
	
	/**
	 * 点击“待受理订单”的处理
	 */
	public void manageAccepted() {
		Log.i(TAG, "manageAccepted");
		Intent mIntent = new Intent();
		mIntent.setClass(ManageActivity.this, ManageAcceptedActivity.class);
        
		startActivity(mIntent);
	}

	/**
	 * 点击“待配送订单”的处理
	 */
	public void manageDelivery() {
		Log.i(TAG, "manageDelivery");
		Intent mIntent = new Intent();
		mIntent.setClass(ManageActivity.this, PendingDeliveryOrdersActivity.class);
		
		startActivity(mIntent);
	}

	/**
	 * 点击“待入账订单”的处理
	 */
	public void manageAccounted() {
		Log.i(TAG, "manageAccounted");
		Intent mIntent = new Intent();
		mIntent.setClass(ManageActivity.this, PendingAccountedOrdersActivity.class);
		
		startActivity(mIntent);
	}

	/**
	 * 点击“账目统计”的处理
	 */
	public void manageStatistics() {
		Log.i(TAG, "manageStatistics");
		Intent mIntent = new Intent();
		mIntent.setClass(ManageActivity.this, AccountsStatisticsActivity.class);
		
		startActivity(mIntent);
	}

	/**
	 * 点击“订单评价”的处理
	 */
	public void manageEvaluation() {
		Log.i(TAG, "manageEvaluation");
		Intent mIntent = new Intent();
		mIntent.setClass(ManageActivity.this, EvaluationActivity.class);
		
		startActivity(mIntent);
	}

	/**
	 * 点击“暂停营业”的处理
	 */
	public void manageSuspendBusiness() {
		Log.i(TAG, "manageSuspendBusiness");
    	if(sp.getBoolean(SPConfig.SUSPENDBUSINESS, false) == false) {
        	quitDialog = new CustomDialog(this, "您确定要暂停营业吗？", false); 
    		quitDialog.show();
    		quitDialog.setDialogConfirmAction(new DialogActionListener() {
				
				@Override
				public void confirmAction() {
//		    		layoutAcceptOrder.setClickable(false);
//		        	layoutPendingDeliveryOrders.setClickable(false);
//		        	layoutPendingAccountedOrdersr.setClickable(false);
					String token = sp.getString(SPConfig.ACCESSTOKEN, "0");
					String shopID = sp.getString(SPConfig.SHOPID, "");
					
					RequestUtils.suspendBusiness(token, shopID, "1", handler, requestList);
		        	quitDialog.dismiss();
					
				}

				@Override
				public void confirmAction(String paramString, String paramString2) {
					// TODO Auto-generated method stub
					
				}
			});
    	} else {
        	quitDialog = new CustomDialog(this, "您确定要恢复营业吗？", false); 
    		quitDialog.show();
    		quitDialog.setDialogConfirmAction(new DialogActionListener() {
				
				@Override
				public void confirmAction() {
//		    		layoutAcceptOrder.setClickable(true);
//		        	layoutPendingDeliveryOrders.setClickable(true);
//		        	layoutPendingAccountedOrdersr.setClickable(true);

					String token = sp.getString(SPConfig.ACCESSTOKEN, "0");
					String shopID = sp.getString(SPConfig.SHOPID, "");
					RequestUtils.suspendBusiness(token, shopID, "2", handler, requestList);
		        	quitDialog.dismiss();
					
				}

				@Override
				public void confirmAction(String paramString, String paramString2) {
					// TODO Auto-generated method stub
					
				}
			});
    	}
	}

	/**
	 * 初始化“暂停营业”
	 */
	public void initSuspendBusiness() {
		Log.i(TAG, "initSuspendBusiness");
		
    	if(sp.getBoolean(SPConfig.SUSPENDBUSINESS, false) == false) {
//			layoutAcceptOrder.setClickable(true);
//		    layoutPendingDeliveryOrders.setClickable(true);
//		    layoutPendingAccountedOrdersr.setClickable(true);

		    tvSuspendBusiness.setText("暂停营业（不接受订单）");
		    tvSuspendBusiness.setTextColor(Color.BLACK);
    		
    	} else {
//		    layoutAcceptOrder.setClickable(false);
//		    layoutPendingDeliveryOrders.setClickable(false);
//		    layoutPendingAccountedOrdersr.setClickable(false);
		        	
		    tvSuspendBusiness.setText("恢复营业（接受订单）");
		    tvSuspendBusiness.setTextColor(Color.BLUE);
    	}
	}
	
	public void notifyUser() {
		sp.setBoolean(SPConfig.NOTIFY, false);
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
		// 2).新建一个通知，指定其图标和标题
		int icon = R.drawable.ic_launcher;
		long when = System.currentTimeMillis();
		// 第一个参数为图标,第二个参数为标题,第三个为通知时间
		Notification notification = new Notification(icon, null, when);

//		notification.defaults |= Notification.DEFAULT_SOUND; 

		notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.msg); 
		notification.defaults |= Notification.DEFAULT_VIBRATE;
		notification.flags |= Notification.FLAG_AUTO_CANCEL; // 自动取消
		
		Intent openintent = new Intent(ManageActivity.this, ManageActivity.class);
		// 当点击消息时就会向系统发送openintent意图
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				openintent, 0);
		notification.setLatestEventInfo(this, "新消息提醒", "您有新的订单，请及时处理", contentIntent);
		
		mNotificationManager.notify(0, notification);
	}
	
	public void cancelNotify() {
		NotificationManager notifi = (NotificationManager) this.getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
		notifi.cancel(0);
	}
	
	/**
	 * 此handler主要是解决登录失败时，页面的toast提示
	 * 因为登录是通过队列异步进行的，不能在线程里处理LoginActivity里的界面
	 */
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) { 
			switch(msg.what) {
			case QUITTIP: //退出失败提示
				loginOutDialog.dismiss();
				ToastUtils.show(ManageActivity.this.mContext, "退出失败，请稍候重试！", ManageActivity.this.getState());
				break;
			case GETSHOPINFOSUCCESS:
				
				/**
				 * 取从服务器返回的数据
				 */
				mShop = (Shop)msg.getData().get(SER_KEY);     
				
				tvShopName.setText(mShop.getShopName());
		        tvLastLoginTime.setText(mShop.getLastLoginTime());
		        tvSuccessfulOrders.setText(mShop.getSuccessfulOrders());
		        tvTotalEvaluation.setText(mShop.getTotalEvaluation());


		        if(mShop.getTaste().length() > 2) {
		        	tvTaste.setText(mShop.getTaste().substring(0, 3));
		        	
		        } else {
		        	tvTaste.setText(mShop.getTaste());
		        }
		        
		        if(mShop.getSpeed().length() > 2) {
		        	tvSpeed.setText(mShop.getSpeed().substring(0, 3));
		        } else {
		        	tvSpeed.setText(mShop.getSpeed());
		        }
		        
		        if(mShop.getService().length() > 2) {
		        	tvService.setText(mShop.getService().substring(0, 3));
		        } else {
		        	tvService.setText(mShop.getService());
		        }
		        
		        tvTurnover.setText(mShop.getTurnover());
				
		        tvAcceptOrderContent.setText(mShop.getAcceptOrder());
		        tvPendingDeliveryOrders.setText(mShop.getDeliverOrder());
		        tvPendingAccountedOrders.setText(mShop.getIncomeOrder());

		        int num = Integer.valueOf(mShop.getAcceptOrder());
		        if(sp.getBoolean(SPConfig.NOTIFY, false) == true) {

			        if(num > 0) {
			        	notifyUser();
			        }
		        }
		        
		        /**
		         * 程序的默认设置，“暂停/恢复营业”
		         */
		        initSuspendBusiness();
		        
				break;
			case GETSHOPINFOFAIL:
				
				break;
			case SUCCESS://暂停/恢复营业成功
		    	if(sp.getBoolean(SPConfig.SUSPENDBUSINESS, false) == false) {
		    		sp.setBoolean(SPConfig.SUSPENDBUSINESS, true);
		        	tvSuspendBusiness.setText("恢复营业（接受订单）");
		        	tvSuspendBusiness.setTextColor(Color.BLUE);
		    	} else {
		    		sp.setBoolean(SPConfig.SUSPENDBUSINESS, false);
		        	tvSuspendBusiness.setText("暂停营业（不接受订单）");
		        	tvSuspendBusiness.setTextColor(Color.BLACK);
		    	}
				break;
			case FAIL:////暂停恢复/营业失败
		    	if(sp.getBoolean(SPConfig.SUSPENDBUSINESS, false) == false) {
		    		Toast.makeText(ManageActivity.this, "暂停营业失败，请稍候重试！", Toast.LENGTH_SHORT).show();
		    	} else {
		    		Toast.makeText(ManageActivity.this, "恢复营业失败，请稍候重试！", Toast.LENGTH_SHORT).show();
		    	}
				
				break;
			default:
				break;
			} 
		};
	};
	
	// 返回登录页面
	// 清空用户登录信息
	public void quit() {
		Log.i(TAG, "quit");
		quitDialog = new CustomDialog(this, "您确定要退出此账户吗？", false); 
		quitDialog.show();
		quitDialog.setDialogConfirmAction(new DialogActionListener() {
			
			@Override
			public void confirmAction() {
				quitDialog.dismiss();
				loginOutDialog = new CustomProgressDialog(ManageActivity.this, "正在退出账户...", "正在退出，请稍侯...");
				loginOutDialog.show();
				logout();
			}

			@Override
			public void confirmAction(String paramString, String paramString2) {
				// TODO Auto-generated method stub
				
			}
		});
	}
	
	/**
	 * 退出账户
	 */
	private void logout() {
		List<RequestParameter> parameterList = new ArrayList<RequestParameter>();
		parameterList.add(new RequestParameter("access_token", sp.getString(SPConfig.ACCESSTOKEN, "0")));
		parameterList.add(new RequestParameter("shopid", mShop.getShopID()));
		
		AsyncHttpGet httpget = new AsyncHttpGet(null, LOGOUTURL, parameterList,
			new RequestResultCallback() {

				@Override
				public void onSuccess(Object o) {
					Log.i("HttpGetExample", "HttpGetExample  request  onSuccess result :"+((String)o).toString());
						
					try{
						JSONObject jsonTemp = new JSONObject(((String)o).toString());
						String quitInfo = jsonTemp.get("quit _return").toString();
						boolean quitSuccess = Boolean.valueOf(quitInfo);
							
						if(quitSuccess == true) {
							clearInfo();
							loginOutDialog.dismiss();
							exit(ManageActivity.this, LoginActivity.class);
						} else {
							Message msg = new Message(); 
					        msg.what = QUITTIP;
					        handler.sendMessage(msg);  //向Handler发送消息
						}
							
					} catch (JSONException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
					
				@Override
				public void onFail(Exception e) {
					loginOutDialog.dismiss();
					Log.i("HttpGetExample", "HttpGetExample  request   onFail :"+((RequestException)e).getMessage());
				}
		});
		
		DefaultThreadPool.getInstance().execute(httpget);
		this.requestList.add(httpget);
	}
	
	/**
	 * 清除用户信息
	 */
	private void clearInfo() {
		sp.setString(SPConfig.USERNAME, "");
		sp.setString(SPConfig.PASSWORD, "");
		sp.setString(SPConfig.ACCESSTOKEN, "0");
	}
	
}
